package com.security.springsecurity02.config;

import com.security.springsecurity02.handler.MyAccessDeniedHandler;
import com.security.springsecurity02.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

//@Configuration
public class AccessConfig extends WebSecurityConfigurerAdapter {

    //@Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("bml").password("111").authorities("admin","user").roles("ROLE_r1","ROLE_r2")
//                .and()
//                .withUser("user").password("111").authorities("admin","user").roles("ROLE_r1","ROLE_r2");
//    }

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();
        http.authorizeRequests()
                .antMatchers("/admin/demo").permitAll()
                .antMatchers("/admin/main").access("hasAnyAuthority('admin')")
                .antMatchers("/admin/query").access("hasRole('r1')")
                .antMatchers("/admin/test").access("@myDefinitionSecurityExpression.hashPermission(request,authentication)");

        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler());
        http.csrf().disable();

        http.userDetailsService(userService);

    }
}
